package session

import (
	"sync"
	"time"

	"gitee.com/githubdog/goci/tools/helper"
)

var (
	sessLock sync.RWMutex
	sessData = map[string]interface{}{}
	SessKey  = "go_session"
)

// SessionTime ..
func SessionTime() time.Duration {
	return time.Hour
}

// SetSession ..
func SetSession(val interface{}) (string, error) {
	var (
		err error
		ret string
	)

	ret = helper.GenerateUUID()
	sessLock.Lock()
	sessData[ret] = val
	sessLock.Unlock()
	// 超时删除
	time.AfterFunc(SessionTime(), func() {
		DelSession(ret)
	})
	return ret, err
}

// GetSession ..
func GetSession(key string) (interface{}, bool) {
	var (
		ret interface{}
		ok  bool
	)

	sessLock.RLock()
	ret, ok = sessData[key]
	sessLock.RUnlock()
	return ret, ok
}

// DelSession delete session
func DelSession(key string) (string, error) {
	var (
		err error
		ret string
	)

	sessLock.RLock()
	delete(sessData, key)
	sessLock.RUnlock()
	return ret, err
}
